package vip.hello520.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import vip.hello520.model.LinkPo;
import vip.hello520.model.ResultBean;
import vip.hello520.service.LinkService;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class LinkController extends BaseController {
    @Autowired
    private LinkService linkService;

    /**
     * 获取友情链接
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/friendLinks.do")
    @ResponseBody
    public List<LinkPo> getLinkPoList() throws Exception {
        return linkService.getLinkPoList();
    }

    /**
     * 返回封装了必应图片的URL和图片名字的map,@ResponseBody会自动转会为json字符串
     *
     * @return
     */
    @RequestMapping(value = "/biYing.do")
    @ResponseBody
    public Map getBiYing(Integer imgIndex) {
        return getBiYingParaMap(imgIndex);
    }

    /**
     * 保存必应图片到服务器
     *
     * @return
     */
    @RequestMapping(value = "/saveImgToRemoto.do")
    @ResponseBody
    public String saveImgToRemote(Integer imgIndex) {
        ResultBean resultBean = new ResultBean();
        Map<String, String> biYingParaMap = getBiYingParaMap(imgIndex);
        String imgUrl = biYingParaMap.get("imgUrl");
        String path = "/usr/rbj/imgs".trim();
        String imgName = biYingParaMap.get("copyright").split("\\(")[0].replace("/", "").trim();
        //获取扩展名
        String extension = imgUrl.substring(imgUrl.lastIndexOf(".", imgUrl.length()));
        //保存图片
        try {
            resultBean = linkService.saveBiYingImgToRemote(imgUrl, path, imgName += extension);
        } catch (Exception e) {
            e.printStackTrace();
            return JSON.toJSONString(resultBean);
        }
        return JSON.toJSONString(resultBean);
    }

    /**
     * 保存图片到本地
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "/saveImgToLocal.do")
    public void saveImgToLocal(Integer imgIndex, HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, String> biYingParaMap = getBiYingParaMap(imgIndex);
        String imgUrl = biYingParaMap.get("imgUrl");
        String imgName = biYingParaMap.get("copyright").split("\\(")[0].replace("/", "").trim();
        // 获取扩展名
        String extension = imgUrl.substring(imgUrl.lastIndexOf(".", imgUrl.length()));
        String name = URLEncoder.encode(imgName += extension, "utf-8");
        //response.setContentType("multipart/form-data");
        //response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + name);
        /*保存图片*/
        doSaveImg(imgUrl, response);

        //fastJSON的用法
        //String biYingString = getBiYingString();
        //JSONObject jsonObject = JSON.parseObject(biYingString);
        //String images = jsonObject.getString("images");
        //String imgStr = images.substring(1, images.length() - 1);
        //JSONObject imgObj = JSON.parseObject(imgStr);
        //String subImgUrl = imgObj.getString("url");
        //String fileName = imgObj.getString("copyright").split("\\(")[0].replace("/", "");
        //String url = "https://cn.bing.com" + subImgUrl;
    }

    /**
     * 保存图片
     *
     * @param fileUrl
     * @param response
     * @return
     */
    private void doSaveImg(String fileUrl, HttpServletResponse response) throws IOException {
        HttpURLConnection con = null;
        URL urlAddress = new URL(fileUrl);
        //打开链接
        con = (HttpURLConnection) urlAddress.openConnection();
        //创建输入流
        try (BufferedInputStream inputStream = new BufferedInputStream(con.getInputStream());
             // 创建输出流
             ServletOutputStream servletOutputStream = response.getOutputStream();
        ) {
            // 缓存数组
            byte[] by = new byte[1024];
            //input读取的字节数
            int len;
            while ((len = inputStream.read(by)) != -1) {
                servletOutputStream.write(by, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (con != null) {
                con.disconnect();
            }
        }
    }

    /**
     * 封装必应图片参数到map
     *
     * @return
     */
    private Map getBiYingParaMap(Integer imgIndex) {
        String biYingStr = "";
        BufferedReader buf = null;
        HttpURLConnection con = null;
        if (imgIndex == null) {
            imgIndex = 0;
        }
        try {
            URL url = new URL("https://cn.bing.com/HPImageArchive.aspx?format=js&idx=" + imgIndex + "&n=1");
            con = (HttpURLConnection) url.openConnection();
            buf = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
            String inputLine;
            while ((inputLine = buf.readLine()) != null) {
                biYingStr += inputLine;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (con != null) {
                con.disconnect();
            }
            if (buf != null) {
                try {
                    buf.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        // 返回的参数集合
        Map<String, String> biYingMap = new HashMap<>();
        JSONObject jsonObject = JSON.parseObject(biYingStr);
        String images = jsonObject.getString("images");
        String imgStr = images.substring(1, images.length() - 1).trim();
        JSONObject imgObj = JSON.parseObject(imgStr);
        String subImgUrl = imgObj.getString("url").trim();
        String copyright = imgObj.getString("copyright");
        String imgUrl = "https://cn.bing.com" + subImgUrl;
        //封装参数到map
        biYingMap.put("imgUrl", imgUrl.trim());
        biYingMap.put("copyright", copyright.trim());
        return biYingMap;
    }
}
